package com.heima.wemedia.filter;

import com.heima.model.common.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Order(1) //过滤器执行先后顺序
@WebFilter(filterName="WmTokenFilter",urlPatterns = "/*") //拦截所有请求
@Log4j2
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求和响应
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //从请求中获取用户UserId
        String userId = request.getHeader("UserId");
        if(userId!=null){
            WmUser user = new WmUser();
            user.setId(Integer.valueOf(userId));
            //放入当前线程中
            WmThreadLocalUtils.setUser(user);
        }

        //放行当前请求
        filterChain.doFilter(request,response);

    }
}
